package com.financing.platform.web.api;

import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.financing.platform.common.Pager;
import com.financing.platform.common.ResultCode;
import com.financing.platform.common.ResultMap;
import com.financing.platform.common.ResultMap.STATUS;
import com.financing.platform.dao.IActivitesDao;
import com.financing.platform.dao.IWxWithdrawLogDao;
import com.financing.platform.dto.AccessInfoDTO;
import com.financing.platform.dto.ActivitesDTO;
import com.financing.platform.dto.FaUserDTO;
import com.financing.platform.dto.FpFaUserDTO;
import com.financing.platform.dto.FpFaUserDataDTO;
import com.financing.platform.dto.FpFileRecordDTO;
import com.financing.platform.dto.UserInfoDTO;
import com.financing.platform.dto.WxWithdrawLogDTO;
import com.financing.platform.dto.vo.FpFaUserVoDTO;
import com.financing.platform.service.IActivitesService;
import com.financing.platform.service.IFaUserService;
import com.financing.platform.service.IFpFaUserService;
import com.financing.platform.service.IUserInfoService;
import com.financing.platform.service.impl.FaUserVisitServiceImpl;
import com.financing.platform.service.impl.FpFaUserDataServiceImpl;
import com.financing.platform.service.impl.FpFaUserServiceImpl;
import com.financing.platform.service.impl.FpFileRecordServiceImpl;
import com.financing.platform.util.CsvExportUtil;
import com.financing.platform.util.DTOdateSet;
import com.financing.platform.util.DateUtil;
import com.financing.platform.vo.FaUserVisitStatisticVO;
import com.financing.platform.vo.JcsYxtActivityVO;
import com.financing.platform.vo.LicashiCountVO;
import com.financing.platform.vo.LicashiDetailVO;
import com.financing.platform.vo.UserAllSumVO;
import com.financing.platform.vo.UserShopRoleVO;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * 理财师店铺
 * 
 * @author zyh
 *
 */
@Controller("ShopAction")
@RequestMapping("/api/shop")
@Scope("prototype")
public class ShopAction extends BaseAction {

	private Logger log = Logger.getLogger(this.getClass());

	@Autowired
	IFaUserService faUserServiceImpl;
	@Autowired
	IUserInfoService userInfoServiceImpl;
	@Autowired
	FaUserVisitServiceImpl faUserVisitServiceImpl;
	@Autowired
	FpFileRecordServiceImpl fpFileRecordServiceImpl;
	
	@Autowired
	FpFaUserDataServiceImpl userDataServiceImpl;
	@Autowired
	FpFaUserServiceImpl userServiceImpl;
	@Autowired
	IWxWithdrawLogDao  drawLogImpl;
	@Autowired
	IFpFaUserService fpfaUserServiceImpl;
	@Autowired
	IActivitesService activtiesServiceImpl;

	@SuppressWarnings("unchecked")
	@RequestMapping("/queryShopUserList.shtml")
	@ResponseBody
	public ResultMap queryFaUserList(HttpServletRequest request, HttpServletResponse response,
			FaUserDTO faUserDTO,
			Pager pager, String adviserUserId) {
		try {
			log.info("Begin query fa user list!");

			if (!StringUtils.isBlank(faUserDTO.getSystemUserId())
					&& ("isnoManagerUser").equals(faUserDTO.getSystemUserId())) {
				faUserDTO.setSystemUserId(null);
			} else {
				if (StringUtils.isBlank(adviserUserId)) {
					List<String> systemUserIds = faUserServiceImpl.queryFaUserSubUserId(faUserDTO.getSystemUserId());
					systemUserIds.add(faUserDTO.getSystemUserId());
					faUserDTO.setSystemUserIds(systemUserIds);
				} else {
					List<String> systemUserIds = new ArrayList<String>();
					systemUserIds.add(adviserUserId);
					faUserDTO.setSystemUserIds(systemUserIds);
				}
			}
			// 判断当前登录者是否是理财师管理员
			HttpSession session = request.getSession();
			UserInfoDTO user = (UserInfoDTO) session.getAttribute(DTOdateSet.user);

			if (!"admin".equals(user.getUserNickname())) {
				boolean isManager = false;
				List<AccessInfoDTO> accessInfoList = user.getAccessList();
				for (AccessInfoDTO access : accessInfoList) {
					if (access.getActionName().equals("addManagerLicaishiUser.shtml")) {
						isManager = true;
						break;
					}
				}
				if (!isManager) {
					faUserDTO.setSystemUserId(user.getUserId());
				}
			}

			faUserDTO.setBegin(pager.getStartIndex());
			faUserDTO.setPageSize(pager.getPageSize());
			// faUserDTO.setuFrom("1");

			int count = faUserServiceImpl.queryAllShopFaUserInfoCount(faUserDTO);
			pager.setTotalCount(count);

			List<FaUserDTO> list;
			if (count > 0) {
				list = faUserServiceImpl.queryAllShopFaUserInfo(faUserDTO);
				for (FaUserDTO fa : list) {
					fa.setuPassWord(null);
					// 查询最后回访时间
					// 查询 回访信息

					FaUserVisitStatisticVO visitStatistic = faUserVisitServiceImpl
							.queryFaUserVisitStatistic(fa.getId());
					fa.setVisitStatisticVO(visitStatistic);
				}
			} else {
				list = Collections.EMPTY_LIST;
			}

			resultMap.setAttribute("list", list);
			resultMap.setAttribute("pager", pager);
			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);

			log.info("End query fa user list!");
		} catch (Exception e) {
			log.error("queryFaUserList error !", e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}

		return resultMap;
	}

	/**
	 * 素材查询
	 * 
	 * @param request
	 * @param response
	 * @param fpFileRecordDTO
	 * @param pager
	 * @param adviserUserId
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/queryShopSucai.shtml")
	@ResponseBody
	public ResultMap queryShopSucai(HttpServletRequest request, HttpServletResponse response,
			FpFileRecordDTO fpFileRecordDTO, Pager pager, String adviserUserId) {
		try {
			log.info("Begin query fa file list!");

			int count = fpFileRecordServiceImpl.queryListCount(fpFileRecordDTO);
			pager.setTotalCount(count);

			List<FpFileRecordDTO> list;
			if (count > 0) {
				list = fpFileRecordServiceImpl.queryList(fpFileRecordDTO);
			} else {
				list = Collections.EMPTY_LIST;
			}

			resultMap.setAttribute("list", list);
			resultMap.setAttribute("pager", pager);
			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);

			log.info("End query fa file list!");
		} catch (Exception e) {
			log.error("queryShopSucai error !", e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}

		return resultMap;
	}

	// 首页管理统计
	@RequestMapping("/queryBehaviorHomeList.shtml")
	@ResponseBody
	public ResultMap queryBehaviorHomeList(HttpServletRequest request, HttpServletResponse response) {
		try {
			String string = "";
			String data = request.getParameter("data");
			if (StringUtils.isEmpty(data)) {
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
				data = sdf.format(new Date());
			}
			URL url = new URL(mongoDBLink + "shopData/shopFrontMeter" + "?monthStart=" + data);
			URLConnection openConnection = url.openConnection();
			InputStream inputStream = openConnection.getInputStream();
			string = IOUtils.toString(inputStream);
			string = string.replaceAll("attributes", "attribute");
			JSONObject json = JSONObject.fromObject(string);
			JSONObject attribute = json.getJSONObject("attribute");
			JSONArray list = attribute.getJSONArray("label1");
			resultMap.setAttribute("list", list);
			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
			return resultMap;
		} catch (IOException e) {
			log.error("queryBehaviorHomeList error !", e);
			return resultMap;
		}
	}

	// 产品管理页统计
	@RequestMapping("/queryBehaviorProdList.shtml")
	@ResponseBody
	public ResultMap queryBehaviorProdList(HttpServletRequest request, HttpServletResponse response) {
		try {
			String string = "";
			String data = request.getParameter("data");

			if (StringUtils.isEmpty(data)) {
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");

				data = sdf.format(new Date());
			}
			URL url = new URL(mongoDBLink + "shopData/shopProductMeter" + "?monthStart=" + data);
			URLConnection openConnection = url.openConnection();
			InputStream inputStream = openConnection.getInputStream();
			string = IOUtils.toString(inputStream);
			string = string.replaceAll("attributes", "attribute");
			JSONObject json = JSONObject.fromObject(string);
			JSONObject attribute = json.getJSONObject("attribute");
			JSONArray list = attribute.getJSONArray("label1");
			resultMap.setAttribute("list", list);
			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
			return resultMap;
		} catch (IOException e) {
			log.error("queryBehaviorHomeList error !", e);
			return resultMap;
		}
	}

	// 客户管理页统计
	@RequestMapping("/queryBehaviorCustList.shtml")
	@ResponseBody
	public ResultMap queryBehaviorCustList(HttpServletRequest request, HttpServletResponse response) {
		try {
			String string = "";
			String data = request.getParameter("data");

			if (StringUtils.isEmpty(data)) {
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");

				data = sdf.format(new Date());
			}
			
			URL url = new URL(mongoDBLink + "shopData/shopMeter" + "?monthStart=" + data + "&type=110600&types=11060");
			URLConnection openConnection = url.openConnection();
			InputStream inputStream = openConnection.getInputStream();
			string = IOUtils.toString(inputStream);
			string = string.replaceAll("attributes", "attribute");
			JSONObject json = JSONObject.fromObject(string);
			JSONObject attribute = json.getJSONObject("attribute");
			JSONArray list = attribute.getJSONArray("label1");
			resultMap.setAttribute("list", list);
			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
			return resultMap;
		} catch (IOException e) {
			log.error("queryBehaviorHomeList error !", e);
			return resultMap;
		}
	}

	// 底部菜单统计
	@RequestMapping("/queryBehaviorFooterMenuList.shtml")
	@ResponseBody
	public ResultMap queryBehaviorFooterMenuList(HttpServletRequest request, HttpServletResponse response) {
		try {
			String string = "";
			String data = request.getParameter("data");

			if (StringUtils.isEmpty(data)) {
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");

				data = sdf.format(new Date());
			}
			URL url = new URL(mongoDBLink + "shopData/shopMeter" + "?monthStart=" + data + "&type=110700&types=11070");
			URLConnection openConnection = url.openConnection();
			InputStream inputStream = openConnection.getInputStream();
			string = IOUtils.toString(inputStream);
			string = string.replaceAll("attributes", "attribute");
			JSONObject json = JSONObject.fromObject(string);
			JSONObject attribute = json.getJSONObject("attribute");
			JSONArray list = attribute.getJSONArray("label1");
			resultMap.setAttribute("list", list);
			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
			return resultMap;
		} catch (IOException e) {
			log.error("queryBehaviorHomeList error !", e);
			return resultMap;
		}
	}
	
	
	// 内部理财师统计
	@RequestMapping("/queryBehaviorFpList.shtml")
	@ResponseBody
	public ResultMap queryBehaviorFpList(HttpServletRequest request, 
			HttpServletResponse response,Pager page) {
		try {
			
			String string = "";
			String data = request.getParameter("data");
			
			if (StringUtils.isEmpty(data)) {
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				data = sdf.format(new Date());
			}
			//查询内部理财师
			String faName=request.getParameter("faName");
			UserInfoDTO userInfoDTO = new UserInfoDTO();
			userInfoDTO.setStatus("0");

			if(StringUtils.isNotBlank(faName)){
				userInfoDTO.setUsername("%"+faName+"%");
			}
			
			List<UserInfoDTO> us = userInfoServiceImpl.queryAllUserInfo(userInfoDTO);
			Map<String,String> userKey =  new HashMap<String,String>();
			String mobiles="";
			for (UserInfoDTO userInfo:us){
				if(StringUtils.isBlank(userInfo.getTelePhone())){
					continue;
				}
				if(userKey.containsKey(userInfo.getTelePhone())){
					continue;
				}
				userKey.put(userInfo.getTelePhone(),userInfo.getTelePhone());
				mobiles+=","+userInfo.getTelePhone();
			}
			if(mobiles.length()>0){
				mobiles=mobiles.substring(1,mobiles.length());
			}
			String getMobile =mobiles;
			//&  查询内部传入   已取消 现在查询全部
			String getIn = request.getParameter("getIn");
			
			if(StringUtils.isNotBlank(getIn) && getIn.equals("11")){
				mobiles = "&mobiles="+mobiles;
			}else{
				mobiles = "";
			}
			//模糊查询固定查询内部
			boolean bl=false;
			if(StringUtils.isNotBlank(faName)){
				mobiles="&mobiles="+getMobile;
				if(StringUtils.isBlank(getMobile)){
					bl=true;
				}
				
			}
			
			String shopurl =  mongoDBLink + "shopData/shopFaUserMeter" + "?monthStart=" + data + "&pageSize="+page.getPageSize()+"&pageNo="+page.getPageNo()+mobiles;
			log.info("shopurl:"+shopurl);
			URL url = new URL(shopurl);
			URLConnection openConnection = url.openConnection();
			InputStream inputStream = openConnection.getInputStream();
			string = IOUtils.toString(inputStream);
			log.info("shopurl string:"+string);
			string = string.replaceAll("attributes", "attribute");
			JSONObject json = JSONObject.fromObject(string);
			JSONObject attribute = json.getJSONObject("attribute");
			JSONArray list = attribute.getJSONArray("list");
			JSONObject pager = attribute.getJSONObject("pager");
			//查询内部理财师名称
			JSONArray jsar= new JSONArray();
			for (int i = 0; i < list.size(); i++) {
				JSONObject js =JSONObject.fromObject(list.get(i));
				for (int j = 0; j < us.size(); j++) {
					if(us.get(j).getTelePhone().equals(js.getString("shopId"))){
						js.element("faName", us.get(j).getUsername());
					}
				}
				js.element("shopId",js.getString("shopId").substring(0,3)+"****"+js.getString("shopId").substring(7,11));
				jsar.add(js);
			}
			if(bl){
				jsar= new JSONArray();
			}
			resultMap.setAttribute("list", jsar);
			resultMap.setAttribute("pager", pager);
			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
			return resultMap;
		} catch (IOException e) {
			log.error("queryBehaviorHomeList error !", e);
			return resultMap;
		}
	}
	/***
	 * 查询内部理财师信息邀请函系统分配统计
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/querylcsmanstatisticsList.shtml")
	@ResponseBody
	public ResultMap querylcsmanstatisticsList(HttpServletRequest request,
			HttpServletResponse response) {
		try {
			// 参数
			Map map = getParameterMap(request);
			
			getSystemIsCurrent(request, map);
			
			List<LicashiCountVO> querylcsstatistics = getlcsman(map);

			resultMap.setAttribute("list", querylcsstatistics);
			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
		} catch (Exception e) {
			log.error("querylcsmanstatisticsList error !", e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}
		return resultMap;
	}
	
	/***
	 * 查询内部理财师详情列表
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/querylcsmanDetailList.shtml")
	@ResponseBody
	public ResultMap querylcsmanDetailList(HttpServletRequest request,
			HttpServletResponse response,Pager pager) {
		try {
			// 参数
			Map map = getParameterMap(request);

			map.put("pager", pager);
			
			getSystemIsCurrent(request, map);
			
			getSystemIds(map);
			
			int count = userInfoServiceImpl.countlcsDetailstatistics(map);
			
			pager.setTotalCount(count);
			
			List<LicashiDetailVO> detail = userInfoServiceImpl.querylcsDetailstatistics(map);
			
			resultMap.setAttribute("pager",pager);
			resultMap.setAttribute("list", detail);
			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
		} catch (Exception e) {
			log.error("querylcsmanstatisticsList error !", e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}
		return resultMap;
	}

	/***
	 * 导出内部理财师详情列表
	 * 
	 * @param request
	 * @param response
	 * @param faUserDTO
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping("/lcsmanDetailCsv.shtml")
	public void lcsmanDetailCsv(HttpServletRequest request,
			HttpServletResponse response) {
		try {
			log.info("Begin lcsmanDetailCsv !");
			// 参数
			Map map = getParameterMap(request);
			
			getSystemIsCurrent(request, map);
			
			getSystemIds(map);
			
			List querylcsstatistics = userInfoServiceImpl.querylcsDetailstatistics(map);
			CsvExportUtil.doCsvExport(response, querylcsstatistics);
			log.info("End lcsmanDetailCsv !");
		} catch (Exception e) {
			log.error("lcsmanDetailCsv error !", e);
		}
		return;
	}

	/**
	 * 获取内部理财师 统计信息
	 * @param map
	 * @return
	 * @throws SQLException
	 */
	private List<LicashiCountVO> getlcsman(Map map) throws SQLException {
		
		getSystemIds(map);
		
		// 内部理财师邀请函
		List<LicashiCountVO> querylcsstatistics = userInfoServiceImpl.querylcsstatistics(map);
		StringBuffer mobiles=new StringBuffer();
		for (LicashiCountVO licashiCountVO : querylcsstatistics) {
			String telephone = licashiCountVO.getTelephone();
			if(StringUtils.isNotBlank(telephone)){
				if(StringUtils.isNotBlank(mobiles.toString())){
					mobiles.append(",");
				}
				mobiles.append(telephone);
			}
		}
		
		// 查询所有的内部理财师的邀请函分享count
		try {
			//获取开始结束时间
			String startDate=map.get("startDate")==null?"":(URLEncoder.encode(map.get("startDate")+"","utf-8"));
			String endDate=map.get("endDate")==null?"":(URLEncoder.encode(map.get("endDate")+"","utf-8"));
			
			Map<String,Integer> res=new HashMap<String, Integer>();
			String u=mongoDBLink + "shopData/getByMobileType" + "?types=110800&monthStart=%s&monthEnd=%s&mobiles=%s";
			URL url = new URL(String.format(u,startDate,endDate,mobiles.toString()));
			URLConnection openConnection = url.openConnection();
			InputStream inputStream = openConnection.getInputStream();
			String result = IOUtils.toString(inputStream);
			JSONObject json = JSONObject.fromObject(result);
			JSONObject attribute = json.getJSONObject("attributes");
			JSONArray list = attribute.getJSONArray("list");
			for (int i=0;i<list.size();i++) {
				JSONObject jsonObject = list.getJSONObject(i);
				res.put(jsonObject.getString("shopId"),jsonObject.getInt("count"));
			}
			for (LicashiCountVO vo : querylcsstatistics) {
				String telephone = vo.getTelephone();
				if (StringUtils.isBlank(telephone)) {
					continue;
				}
				Integer shareCount = res.get(telephone);
				vo.setShareCount(shareCount);
			}
		} catch (Exception e) {
			log.error("getlcsman error",e);
		}
		
//		// 内部理财师系统分配   逻辑变更（已分配为主）
//		Map<String, String> querymanstatistics = userInfoServiceImpl
//				.querymanstatistics(map);
//		// 查询所有的内部理财师的邀请函分享count
//		for (LicashiCountVO vo : querylcsstatistics) {
//			String telephone = vo.getTelephone();
//
//			if (StringUtils.isBlank(telephone)) {
//				continue;
//			}
//
//			// 根据手机号 获取系统分配的理财师 统计
//			String count = querymanstatistics.get(telephone);
//			if (StringUtils.isNotBlank(count)) {
//				String[] sysCount = count.split(",");
//				vo.setSysCount(Integer.parseInt(sysCount[0]));
//				vo.setSysRegCount(Integer.parseInt(sysCount[1]));
//				vo.setSysAuthCount(Integer.parseInt(sysCount[2]));
//			} else {
//				log.info("querylcsmanstatisticsList sysCount is null");
////				vo.setSysCount(0);
////				vo.setSysRegCount(0);
////				vo.setSysAuthCount(0);
//			}
//		}
//		// 按邀请函吸引认证会员数+系统分配客户认证会员数按从多至少排序
//		Collections.sort(querylcsstatistics,
//		new Comparator<LicashiCountVO>() {
//			@Override
//			public int compare(LicashiCountVO o1,
//					LicashiCountVO o2) {
//				int regAuthCount1 = o1.getShareAuthCount();
//				int regAuthCount2 = o2.getShareAuthCount();
//				if (regAuthCount1 == regAuthCount2) {
//					int sysAuthCount1 = o1.getSysAuthCount();
//					int sysAuthCount2 = o2.getSysAuthCount();
//					return sysAuthCount2 - sysAuthCount1;
//				}
//				return regAuthCount2 - regAuthCount1;
//			}
//		});
		return querylcsstatistics;
	}

	/***
	 * 导出内部理财师信息邀请函系统分配统计
	 * 
	 * @param request
	 * @param response
	 * @param faUserDTO
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping("/lcsmanstatisticsCsv.shtml")
	public void lcsmanstatisticsCsv(HttpServletRequest request,
			HttpServletResponse response) {
		try {
			log.info("Begin lcsmanstatisticsCsv !");
			// 参数
			Map map = getParameterMap(request);
			getSystemIsCurrent(request, map);
			List getlcsman = getlcsman(map);
			CsvExportUtil.doCsvExport(response, getlcsman);
			log.info("End lcsmanstatisticsCsv !");
		} catch (Exception e) {
			log.error("lcsmanstatisticsCsv error !", e);
		}
		return;
	}
	
	// 关键字数据汇总统计
	@RequestMapping("/cruxdata.shtml")
	@ResponseBody
	public ResultMap cruxdata(HttpServletRequest request, 
			HttpServletResponse response,Pager page) {
		try {
			
			String monthStart = request.getParameter("monthStart");
			String monthEnd = request.getParameter("monthEnd");
			if(StringUtils.isNotBlank(monthStart)){
				monthStart="&monthStart="+monthStart;
			}else{
				monthStart="";
			}	
			if(StringUtils.isNotBlank(monthEnd)){
				monthEnd="&monthEnd="+monthEnd;
			}else{
				monthEnd="";
			}
			
			String shopurl =  mongoDBLink + "shopData/getAll" + "?&pageSize="+page.getPageSize()+"&pageNo="+page.getPageNo()+monthStart+monthEnd;
			
			URL url = new URL(shopurl);
			URLConnection openConnection = url.openConnection();
			InputStream inputStream = openConnection.getInputStream();
			String string = IOUtils.toString(inputStream);
			log.info("shopurl string:"+string);
			string = string.replaceAll("attributes", "attribute");
			JSONObject json = JSONObject.fromObject(string);
			JSONObject attribute = json.getJSONObject("attribute");
			JSONArray list = attribute.getJSONArray("list");
			JSONObject pager = attribute.getJSONObject("pager");
			
			resultMap.setAttribute("list", list);
			resultMap.setAttribute("pager", pager);
			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
			return resultMap;
		} catch (Exception e) {
			// TODO: handle exception
			return resultMap;
		}
	}
	
	
	// 客户注册情况统计  优化前
	@RequestMapping("/custregisterOld.shtml")
	@ResponseBody
	public ResultMap custregisterOld(HttpServletRequest request, 
			HttpServletResponse response,Pager page) {
		try {
			SimpleDateFormat day = new SimpleDateFormat("yyyy-MM-dd");
			
			FpFaUserDTO userDTO = new FpFaUserDTO();
			userDTO.setIsRegister("1");//是否注册 1是0否
			
		
			HashMap<Object,Object> map = this.jcsCustregister(userDTO);
			
			HashMap<Object,Object> sfamap = new HashMap<Object,Object>();
			userDTO.setUFrom("99");
			int alls =  userServiceImpl.queryListCount(userDTO);  //总注册数
			userDTO.setUFrom(null);
			sfamap.put("all", alls);
			sfamap.put("dayall", alls);
			if(map.get("uo")!=null){
				List<UserShopRoleVO> us= (List<UserShopRoleVO>) map.get("uo");
				for (int i = 0; i < us.size(); i++) {
					if(StringUtils.isBlank(us.get(i).getuFrom()) || us.get(i).getuFrom().equals("0")){
						if(!us.get(i).getuShoprole().equals("1")&& 
							!us.get(i).getuShoprole().equals("98")&&
							!us.get(i).getuShoprole().equals("99")){
							us.get(i).setuShoprole("2");
						}
						
						if(us.get(i).getuShoprole().equals("99")){
							sfamap.put("role99", us.get(i).getCount());
						}else if(us.get(i).getuShoprole().equals("1")){
							sfamap.put("role1", us.get(i).getCount());
						}else if(us.get(i).getuShoprole().equals("2")){
							sfamap.put("role2", us.get(i).getCount());
						}else if(us.get(i).getuShoprole().equals("98")){
							sfamap.put("role98", us.get(i).getCount());
						}
					}else if(us.get(i).getuFrom().equals("1") && 
							StringUtils.isNotBlank(us.get(i).getuShoprole())){
						if(us.get(i).getuShoprole().equals("2")){
							map.put("shopRole2", us.get(i).getCount());  
						}else if(us.get(i).getuShoprole().equals("1")){
							map.put("shopRole1", us.get(i).getCount()); 
						}else if(us.get(i).getuShoprole().equals("98")){
							map.put("shopRole98", us.get(i).getCount()); 
						}else if(us.get(i).getuShoprole().equals("99")){
							map.put("shopRole99", us.get(i).getCount()); 
						}
					}
				}
			}
			
//			//sfa
//			HashMap<Object,Object> sfamap = this.sfaCustregister(userDTO, request, response, page);
			//---------------------时间段查询  默认七天
			
			String monthStart = request.getParameter("monthStart");
			String monthEnd = request.getParameter("monthEnd");
			if(StringUtils.isBlank(monthStart)){
				userDTO.setMonthStart(day.format(DateUtil.addDay(new Date(),-6)));
			}else{
				userDTO.setMonthStart(monthStart);
			}
			if(StringUtils.isBlank(monthEnd)){
				userDTO.setMonthEnd(day.format(new Date()));
			}else{
				userDTO.setMonthEnd(monthEnd);
			}
			
			String getPt = request.getParameter("getPt");
			
			
			userDTO.setWhos("1");
			List<FpFaUserVoDTO> us = userServiceImpl.queryBySfaTimeCount(userDTO);  //sfa查询所有认证
			//合并认证状态
			for (int i = 0; i < us.size(); i++) {
				if(!us.get(i).getuRole().equals("1")|| 
					!us.get(i).getuRole().equals("98")||
					!us.get(i).getuRole().equals("99")){
					us.get(i).setuRole("2");
				}
			}
			
			userDTO.setWhos("2");
			List<FpFaUserVoDTO> usNow = userServiceImpl.queryBySfaTimeCount(userDTO);  //sfa查询当日注册
			//金策师查询
			userDTO.setWhos("3");
			List<FpFaUserVoDTO> shopUs = userServiceImpl.queryBySfaTimeCount(userDTO);  //查询所有认证
			//合并认证状态
			userDTO.setWhos("4");
			List<FpFaUserVoDTO> shopUsNow = userServiceImpl.queryBySfaTimeCount(userDTO);  //查询当日注册
			
			//查询当日未认证的用户sfa
			userDTO.setURole("1");
			userDTO.setUFrom("99");
			List<FpFaUserVoDTO> role1Now = userServiceImpl.queryBySfaNowDayRole1(userDTO);
			
			userDTO.setURole(null);
			userDTO.setUShoprole("1");
			userDTO.setUFrom("1");
			List<FpFaUserVoDTO> shopRole1Now = userServiceImpl.queryBySfaNowDayRole1(userDTO);
			
			//转增
			userDTO.setWhos("99");
			List<FpFaUserVoDTO> sfaZ = userServiceImpl.queryByJcsCount(userDTO);
			
			
			long ss= DateUtil.dateDiff(userDTO.getMonthStart().replace("-", ""),userDTO.getMonthEnd().replace("-", ""));
			
			
			List<Object> l = new ArrayList<Object>();
			
			for (int i = 0; i<=ss; i++) {
				HashMap<Object,Object> m= new HashMap<Object,Object>();
				HashMap<Object,Object> m1= new HashMap<Object,Object>();
				String d = day.format(DateUtil.addDay(day.parse(userDTO.getMonthEnd()),-i));
				m.put("date", d);
				m.put("pt", "sfa");
				m1.put("date", d);
				m1.put("pt", "jcs");
				m.put("uRole2", 0);
				m1.put("uRole2", 0);
				for (int j = 0; j < us.size(); j++) {
					if(us.get(j).getuRole().equals("1")){
						continue;
					}
					if(us.get(j).getAuthDate().equals(d)){
						if(us.get(j).getuRole().equals("2")){
							m.put("uRole"+us.get(j).getuRole(),
							Integer.valueOf(m.get("uRole2").toString())+us.get(j).getCount());
						}else{
							m.put("uRole"+us.get(j).getuRole(),us.get(j).getCount());
						}
					}
				}
				
				for (int j = 0; j < role1Now.size(); j++) {
					if(role1Now.get(j).getCreateDate().equals(d)){
						if(role1Now.get(j).getuRole().equals("1")){
							m.put("uRole1",role1Now.get(j).getCount());
						}
					}
				}
				for (int j = 0; j < shopRole1Now.size(); j++) {
					if(shopRole1Now.get(j).getCreateDate().equals(d)){
						if(shopRole1Now.get(j).getuRole().equals("1")){
							m1.put("uRole1",shopRole1Now.get(j).getCount());
						}
					}
				}
				
				
				//认证循环
				for (int j = 0; j < shopUs.size(); j++) {
					if(StringUtils.isBlank(shopUs.get(j).getuShoprole()) 
							|| shopUs.get(j).getuShoprole().equals("1")){
						continue;
					}
					if(shopUs.get(j).getAuthDate().equals(d) 
							&& StringUtils.isNotBlank(shopUs.get(j).getuShoprole())){
						m1.put("uRole"+shopUs.get(j).getuShoprole(),shopUs.get(j).getCount());
					}
				}
				
				for (int j = 0; j < usNow.size(); j++) {
					if(usNow.get(j).getCreateDate().equals(d)){
						m.put("news", usNow.get(j).getCount());
					}
				}
				for (int j = 0; j < shopUsNow.size(); j++) {
					if(shopUsNow.get(j).getCreateDate().equals(d)){
						m1.put("news", shopUsNow.get(j).getCount());
					}
				}
				for (int j = 0; j < sfaZ.size(); j++) {
					if(sfaZ.get(j).getCreateDate().equals(d)){
						m1.put("sfaZjcs", sfaZ.get(j).getCount());
					}
				}
				
				if(StringUtils.isNotBlank(getPt) && getPt.equals("sfa")){
					page.setTotalCount((int) ss);
					l.add(m);
				}else if(StringUtils.isNotBlank(getPt) && getPt.equals("jcs")){
					page.setTotalCount((int) ss);
					l.add(m1);	
				}else{
					l.add(m);
					l.add(m1);	
				}
			}
			
			
			page.setTotalCount(l.size());
			
			int allSize = page.getTotalCount();
			
			if(allSize>page.getPageSize()*page.getPageNo()){
				allSize=page.getPageSize()*page.getPageNo();
			}
			SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm");
			resultMap.setAttribute("l", l.subList(page.getPageSize()*(page.getPageNo()-1), allSize));
			resultMap.setAttribute("jcs", map);
			resultMap.setAttribute("ww", shopRole1Now);
			resultMap.setAttribute("times", fmt.format(new Date()));
			resultMap.setAttribute("sfa", sfamap);
			resultMap.setAttribute("pager", page);
			resultMap.setAttribute("shopUs", shopUs);
			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
			return resultMap;
		} catch (Exception e) {
			e.printStackTrace();
			// TODO: handle exception
			return resultMap;
		}
	}
	
	
	// 客户注册情况统计  优化后
	@RequestMapping("/custregister.shtml")
	@ResponseBody
	public ResultMap custregister(HttpServletRequest request, 
			HttpServletResponse response,Pager page) {
		try {
			SimpleDateFormat day = new SimpleDateFormat("yyyy-MM-dd");
			
			FpFaUserDTO userDTO = new FpFaUserDTO();
			userDTO.setIsRegister("1");//是否注册 1是0否
			
		
			HashMap<Object,Object> map = this.jcsCustregister(userDTO);
			
			HashMap<Object,Object> sfamap = new HashMap<Object,Object>();
			userDTO.setUFrom("99");
			int alls =  userServiceImpl.queryListCount(userDTO);  //总注册数
			userDTO.setUFrom(null);
			sfamap.put("all", alls);
			sfamap.put("dayall", alls);
			if(map.get("uo")!=null){
				List<UserShopRoleVO> us= (List<UserShopRoleVO>) map.get("uo");
				for (int i = 0; i < us.size(); i++) {
					if(StringUtils.isBlank(us.get(i).getuFrom()) || us.get(i).getuFrom().equals("0")){
						if(!us.get(i).getuShoprole().equals("1")&& 
							!us.get(i).getuShoprole().equals("98")&&
							!us.get(i).getuShoprole().equals("99")){
							us.get(i).setuShoprole("2");
						}
						
						if(us.get(i).getuShoprole().equals("99")){
							sfamap.put("role99", us.get(i).getCount());
						}else if(us.get(i).getuShoprole().equals("1")){
							sfamap.put("role1", us.get(i).getCount());
						}else if(us.get(i).getuShoprole().equals("2")){
							sfamap.put("role2", us.get(i).getCount());
						}else if(us.get(i).getuShoprole().equals("98")){
							sfamap.put("role98", us.get(i).getCount());
						}
					}else if(us.get(i).getuFrom().equals("1") && 
							StringUtils.isNotBlank(us.get(i).getuShoprole())){
						if(us.get(i).getuShoprole().equals("2")){
							map.put("shopRole2", us.get(i).getCount());  
						}else if(us.get(i).getuShoprole().equals("1")){
							map.put("shopRole1", us.get(i).getCount()); 
						}else if(us.get(i).getuShoprole().equals("98")){
							map.put("shopRole98", us.get(i).getCount()); 
						}else if(us.get(i).getuShoprole().equals("99")){
							map.put("shopRole99", us.get(i).getCount()); 
						}
					}
				}
			}
			
//				//sfa
//				HashMap<Object,Object> sfamap = this.sfaCustregister(userDTO, request, response, page);
			//---------------------时间段查询  默认七天
			FpFaUserDTO uDTO = new FpFaUserDTO();
			String monthStart = request.getParameter("monthStart");
			String monthEnd = request.getParameter("monthEnd");
			if(StringUtils.isBlank(monthStart)){
				uDTO.setMonthStart(day.format(DateUtil.addDay(new Date(),-6)));
			}else{
				uDTO.setMonthStart(monthStart);
			}
			if(StringUtils.isBlank(monthEnd)){
				uDTO.setMonthEnd(day.format(new Date()));
			}else{
				uDTO.setMonthEnd(monthEnd);
			}
			//查询 统计
			String getPt = request.getParameter("getPt");
			if(StringUtils.isNotBlank(getPt) && getPt.equals("sfa")){
				uDTO.setUFrom("99");
			}else if(StringUtils.isNotBlank(getPt) && getPt.equals("jcs")){
				uDTO.setUFrom("1");	
			}
			
			
			List<UserAllSumVO> s = userServiceImpl.queryBYAllSum(uDTO);
			
			page.setTotalCount(s.size());
			
			int allSize = page.getTotalCount();
			
			if(allSize>page.getPageSize()*page.getPageNo()){
				allSize=page.getPageSize()*page.getPageNo();
			}
			SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm");
			resultMap.setAttribute("l", s.subList(page.getPageSize()*(page.getPageNo()-1), allSize));
			resultMap.setAttribute("jcs", map);
			resultMap.setAttribute("times", fmt.format(new Date()));
			resultMap.setAttribute("sfa", sfamap);
			resultMap.setAttribute("pager", page);
			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
			return resultMap;
		} catch (Exception e) {
			e.printStackTrace();
			// TODO: handle exception
			return resultMap;
		}
	}
	
	
	public HashMap<Object,Object> sfaCustregister(FpFaUserDTO userDTO,HttpServletRequest 
			request,HttpServletResponse response,Pager page) throws SQLException {
		
		HashMap<Object,Object> sfamap = new HashMap<Object,Object>();
		userDTO.setUShoprole(null);
		userDTO.setUFrom("99"); //查询sfa
		userDTO.setURole("1,98,99");
		int role2 =  userServiceImpl.queryListCount(userDTO); //认证通过
		userDTO.setURole("1");
		int role1 =  userServiceImpl.queryListCount(userDTO);  //未提交认证
		userDTO.setURole("98");
		int role98 =  userServiceImpl.queryListCount(userDTO);  //认证中
		userDTO.setURole("99");
		int role99 =  userServiceImpl.queryListCount(userDTO);  //认证失败
		sfamap.put("role99", role99);
		sfamap.put("role1", role1);
		sfamap.put("role2", role2);
		sfamap.put("role98", role98);
		
		userDTO.setURole(null);
		
		int alls =  userServiceImpl.queryListCount(userDTO);  //总注册数
		userDTO.setCreateDate(new Date());
//		int dayalls =  userServiceImpl.queryListCount(userDTO);  //总注册数
		sfamap.put("all", alls);
		sfamap.put("dayall", alls);
		
		
		return sfamap;
	}
	public HashMap<Object,Object> jcsCustregister(FpFaUserDTO userDTO) throws SQLException {
		
		HashMap<Object,Object> map = new HashMap<Object,Object>();
		int All = userDataServiceImpl.queryListCount(new FpFaUserDataDTO()); //总注册数
//		userDTO.setCreateDate(new Date());
		userDTO.setUFrom("1");
		int jcsAll = userServiceImpl.queryListCount(userDTO); //当日新增
		//查询转增数
		userDTO.setCreateDate(null);
		int sfaAll = userServiceImpl.queryBySfaCount(userDTO); //当日转新增
		//查询总认证通过人数
		List<UserShopRoleVO> uo =  userServiceImpl.queryListCountByUshopRole(userDTO); //认证通过
		
		map.put("all", All);   //新增总
		map.put("jcsAll", jcsAll);        //金策师新增数
		map.put("sfaAll", sfaAll);        //sfa转金策师新增数
		map.put("uo", uo);
//		map.put("shopRole2", shopRole2);  
//		map.put("shopRole1", shopRole1);
//		map.put("shopRole98", shopRole98);
//		map.put("shopRole99", shopRole99);
		
		return map;
	}
	
	
	
	// 英雄帖活动统计
	@RequestMapping("/yxtActivity.shtml")
	@ResponseBody
	public ResultMap yxtActivity(HttpServletRequest request, 
			HttpServletResponse response) {
		try {
			String monthStart = request.getParameter("monthStart");
			String monthEnd = request.getParameter("monthEnd");
			
			//查询活动时间
			ActivitesDTO act = activtiesServiceImpl.searchActivitesByCode("JCSYXT");
			
			SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		
			if(StringUtils.isBlank(monthStart)){
				monthStart=fmt.format(act.getActiviesStartTime());
			}else{
				monthStart+=" 00:00:00";
			}
			if(StringUtils.isBlank(monthEnd)){
				monthEnd=fmt.format(act.getActiviesEndTime());
			}else{
				monthEnd+=" 23:59:59";
			}
			
			FpFaUserDTO faUser = new FpFaUserDTO();
			faUser.setMonthStart(monthStart);
			faUser.setMonthEnd(monthEnd);
			faUser.setActivitiesSource("JCSYXT");
			//查询新注册数
			faUser.setWhos("1");
			List<JcsYxtActivityVO> news =userServiceImpl.queryActivityCount(faUser);  
			faUser.setWhos("2");
			List<JcsYxtActivityVO> newsRole =userServiceImpl.queryActivityCount(faUser);
			faUser.setWhos("3");
			List<JcsYxtActivityVO> allIn =userServiceImpl.queryActivityCount(faUser);
			TreeMap<Object,Object> m1= new TreeMap<Object,Object>();
			TreeMap<Object,Object> m2= new TreeMap<Object,Object>();
			TreeMap<Object,Object> m3= new TreeMap<Object,Object>();
			for (int i = 1; i <=10; i++) {
				
				if(news.size()>=i){
					m1.put("V"+news.get(i-1).getUserSource(), news.get(i-1).getCount());
				}
				if(newsRole.size()>=i){
					m2.put("V"+newsRole.get(i-1).getUserSource(), newsRole.get(i-1).getCount());
				}
				if(allIn.size()>=i){
					m3.put("V"+allIn.get(i-1).getUserSource(), allIn.get(i-1).getCount());
				}
			}
			resultMap.setAttribute("news", m1);
			resultMap.setAttribute("news1", news);
			resultMap.setAttribute("newsRole", m2);
			resultMap.setAttribute("allIn", m3);
			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
			return resultMap;
		} catch (Exception e) {
			e.printStackTrace();
			// TODO: handle exception
			return resultMap;
		}
	}
	
	
	// 英雄帖活动提现列表
	@RequestMapping("/yxtActivityDraw.shtml")
	@ResponseBody
	public ResultMap yxtActivityDraw(HttpServletRequest request, 
			Pager pager,HttpServletResponse response) {
		try {
			String mobile= request.getParameter("mobile");
			String activityCode = request.getParameter("activityCode");
			
			WxWithdrawLogDTO widthDraw = new WxWithdrawLogDTO();
			if(StringUtils.isNotBlank(mobile)){
				widthDraw.setMobile(mobile);
			}
			widthDraw.setActivityCode(activityCode);
			List<WxWithdrawLogDTO> count = drawLogImpl.queryAndFaUser(widthDraw);
			pager.setTotalCount(count.size());
			widthDraw.setBegin(pager.getStartIndex());
			widthDraw.setPageNo(pager.getPageNo());
			widthDraw.setPageSize(pager.getPageSize());
			
			List<WxWithdrawLogDTO> wd = drawLogImpl.queryAndFaUser(widthDraw);
			
			WxWithdrawLogDTO w = new WxWithdrawLogDTO();
			w.setWithdrawStatus("02"); //查询成功
			w.setActivityCode(activityCode);
			BigDecimal allbg = drawLogImpl.sunDraw(w);
			SimpleDateFormat day = new SimpleDateFormat("yyyy-MM-dd");
			w.setDay("%"+day.format(new Date())+"%");
			BigDecimal now = drawLogImpl.sunDraw(w);
			
			resultMap.setAttribute("news", wd);
			resultMap.setAttribute("all", allbg);
			resultMap.setAttribute("now", now);
			resultMap.setAttribute("page", pager);
			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
			return resultMap;
		} catch (Exception e) {
			e.printStackTrace();
			// TODO: handle exception
			return resultMap;
		}
	}
	
	
	
}